package task

import (
	"context"
	"cronjob_work/internal/dao"
	"cronjob_work/internal/model/entity"
	"cronjob_work/internal/service"
	"github.com/gogf/gf/v2/frame/g"
)

const (
	TASK_SUCCESS = 0  // 任务执行成功
	TASK_ERROR   = -1 // 任务执行出错
	TASK_TIMEOUT = -2 // 任务执行超时
)

type sTask struct {
}

func (s *sTask) Update(ctx context.Context, condition g.Map, data g.Map) error {
	_, err := dao.PpTask.Ctx(ctx).Where(condition).Update(data)
	return err
}

func (s *sTask) TaskGetList(ctx context.Context, page, pageSize int, filters ...interface{}) ([]*entity.PpTask, int64) {
	offset := (page - 1) * pageSize

	tasks := make([]*entity.PpTask, 0)

	query := dao.PpTask.Ctx(ctx)
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			query = query.Where(filters[k].(string), filters[k+1])
		}
	}

	total, _ := query.Count()
	query.OrderDesc("id").Limit(pageSize, offset).Scan(&tasks)
	return tasks, int64(total)
}

func (s *sTask) TaskGetById(ctx context.Context, id int) (*entity.PpTask, error) {
	var task *entity.PpTask
	err := dao.PpTask.Ctx(ctx).Where("id=?", id).Scan(&task)
	return task, err
}

func init() {
	service.RegisterTask(New())
}

func New() *sTask {
	return &sTask{}
}
